package ch01.thread;

/**
 * Created by zc on 2016/11/7.
 */
public class ProductConsume3 {

    public static void main(String[] args){
        Info03 info=new Info03();
        Product03 pro=new Product03(info);
        Consume03 con=new Consume03(info);
        new Thread(pro).start();
        new Thread(con).start();
    }
}

class Consume03 implements Runnable {
    private Info03 info03;

    public Consume03(Info03 info03) {
        this.info03 = info03;
    }

    @Override
    public void run() {
        for(int i=0;i<10;i++)
        {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.info03.get();
        }
    }
}

class Product03 implements Runnable {
    private Info03 info03 = null;

    public Product03(Info03 info03) {
        this.info03 = info03;
    }

    @Override
    public void run() {
        boolean flag = false;
        for(int i=0; i<10; i++){
            if(flag){
                this.info03.set("Name A", "Content A");
                flag = false;
            } else {
                this.info03.set("Name B", "Content B");
                flag = true;
            }
        }
    }
}
class Info03 {
    private String name;
    private String content;
    private  boolean flag = true;

    public synchronized void set(String name, String content){
        if(!flag){
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        this.name=name;
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.content = content;
        flag = false;
        super.notify();
    }

    public synchronized void get(){
        if(flag){
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(this.name + "--- 饰演 --> " + this.content);
        flag = true;
        super.notify();
    }
}